package com.vf.admin.utils;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.concurrent.CircuitBreaker;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;

public class HttpClient {

    private static final int CONNECTION_REQUEST_TIMEOUT = 30000;
    private static final int SOCKET_TIMEOUT = 50000;
    private static final String UTF_8 = "UTF-8";

    public HttpClient() {
    }

    public static String doPost(String url, Map<String, String> paraMap) {
        CloseableHttpClient client = HttpClients.createDefault();
        String result = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(getDefaultRequestConfig());
            httpPost.setEntity(new UrlEncodedFormEntity(convert(paraMap), UTF_8));
            HttpResponse response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, UTF_8);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static RequestConfig getDefaultRequestConfig() {
        return RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT)
                .build();
    }

    public static List<NameValuePair> convert(Map<String, String> paraMap) {
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        if (ObjectUtils.isEmpty(paraMap)) {
            return nameValuePairs;
        }
        Set<String> keySet = paraMap.keySet();
        for (String key : keySet) {
            nameValuePairs.add(new BasicNameValuePair(key, paraMap.get(key)));
        }
        return nameValuePairs;
    }

}
